<template>
  <div class="upload-oss">
    <van-uploader :after-read="onRead" :before-read="beforeRead" :accept="fileType" v-model="fileList" :multiple="multiple" :max-count="maxCount" :max-size="isOverSize" @oversize="onOversize" @delete="deleteFile"> </van-uploader>
  </div>
  <p class="tips">
    <slot name="tips">
      {{ tips }}
    </slot>
  </p>
</template>

<script setup lang="ts">
import { showToast } from 'vant'
import { upload } from '@/api/common/index'
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {
      return []
    }
  },
  maxCount: {
    // 图片张数
    type: Number,
    default: 6
  },
  maxSize: {
    // 图片大小M
    type: Number,
    default: 10
  },
  fileType: {
    // 文件类型
    type: String,
    default: 'image/*'
  },
  multiple: {
    type: Boolean,
    default: true
  },
  tips: {
    // 说明注意事项
    type: String,
    default: ''
  }
  //   fileList: {
  //     //已上传的文件列表
  //     type: Array,
  //     default: () => {
  //       return []
  //     }
  //   }
})

const fileList = ref<any[]>([]) //附件显示
const dtoFj = ref<any[]>([]) //上传成功后的附件信息
// 文件大小超过限制时触发
const onOversize = (file: any) => {
  file.status = 'failed'
}
//文件大小限制
function isOverSize(file: any) {
  let flag = false
  const fsz = file.size / 1024 / 1024
  const lfsz = props.maxSize
  if (fsz > lfsz) {
    // 校验文件大小

    showToast(`文件大小：${fsz}M，已经超过了${props.maxSize}M，无法上传`)
    flag = true
  }
  return flag
}

// 上传前置处理
function beforeRead(file: any) {
  const accepts = props.fileType.split(',')
  if (Array.isArray(file)) {
    file.forEach(item => {
      const type = item.type.toLowerCase()
      if (!accepts.includes(type)) {
        showToast('请上传正确格式图片')
        return false
      }
    })
  } else if (props.fileType !== 'image/*') {
    const type = file.type.toLowerCase()
    if (!accepts.includes(type)) {
      showToast('请上传正确格式图片')
      return false
    }
  }
  return true
}

function onRead(file: any) {
  let content = file
  let forms = new FormData()
  // 判断当前上传几张图，一张以上则为数组结构
  if (Array.isArray(content)) {
    content.forEach(item => {
      forms.append('file', item.file)
    })
  } else {
    forms.append('file', content.file)
  }
  file.status = 'uploading'
  upload(forms)
    .then(res => {
      if (res) {
        file.status = 'success'
        let obj = {
          data: res,
          status: file.status
        }
        dtoFj.value.push(obj)
      }
    })
    .catch(() => {
      file.status = 'failed'
      let obj = {
        data: '',
        status: file.status
      }
      dtoFj.value.push(obj)
    })
}

//删除
const deleteFile = (file: any, info: any) => {
  dtoFj.value.splice(info.index, 1)
}

//监听数据的变化
watch(
  () => dtoFj.value,
  val => {
    let data = val.filter(item => item.status === 'success').map(item => item.data)
    emit('update:modelValue', data)
  },
  { immediate: true, deep: true }
)
</script>

<style scoped lang="scss">
.tips {
  color: #999;
  font-size: 12px;
}
</style>
